<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <button @click="show = 'child1'">btn1</button>
      <button @click="show = 'child2'">btn2</button>
      <button @click="show = 'child3'">btn3</button>
      <!-- <child1 v-if="show === 1"></child1>
      <child2 v-if="show === 2"></child2>
      <child3 v-if="show === 3"></child3> -->

      <!-- vue提供的组件, 需要配合is属性, is里面写的是组件名称 -->
      <!-- keep-alive是叫缓存组件, 当组件进行切换的时候，不会被销毁和重新创建 -->
      <keep-alive>
        <component :is="show"></component>
      </keep-alive>
    </div>

    <script src="../../Vue.js"></script>
    <script>
      Vue.component("child1", {
        template: `
          <div>child1组件</div>
        `,
      });
      // 动态组件在切换的时候，是会被销毁和重新渲染的
      let timer;
      Vue.component("child2", {
        data() {
          return {
            count: 0,
          };
        },
        template: `
          <div>child2组件 - {{ count }}</div>
        `,
        mounted() {
          console.log("child2 mounted");
          // timer = setInterval(() => {
          //   this.count++;
          // }, 1000);
        },
        beforeDestroy() {
          console.log("child2 destroy");
          clearInterval(timer);
        },
        // 被keep-alive缓存的组件激活时调用
        activated() {
          console.log("activeted");
          timer = setInterval(() => {
            this.count++;
          }, 1000);
        },
        // 被keep-alive缓存的组件失活时调用
        deactivated() {
          console.log("deactiveted");
          clearInterval(timer);
        },
      });
      Vue.component("child3", {
        template: `
          <div>child3组件</div>
        `,
      });

      new Vue({
        el: "#app",
        data() {
          return {
            show: "child1",
          };
        },
      });
    </script>
  </body>
</html>
